package com.sz.ruichar.utils.system.wechat;

import java.io.IOException;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.sz.ruichar.entity.model.constant.Constant;

/**
 * @author Administrator
 * 获取token 同时进行超时重试机制
 */
public class AccessTokenUtil 
{
	private static final Logger LOGGER = LoggerFactory.getLogger(AccessTokenUtil.class);
	public static final long OUTTIME = 7000*1000;//超时时间7200秒之内的值
	private static String accessToken = "";
	private static long startTime = 0L;
	public synchronized static String getAccessToken(String wechatAppId,String wechatAppSecret)
	{
		long now = System.currentTimeMillis();
		if(StringUtils.isEmpty(accessToken) || now - startTime > OUTTIME)
		{
			String getAccessTokenUrl = Constant.WECHAT_ACCESS_TOKEN_URL.replace("APPID", wechatAppId)
			.replace("APPSECRET", wechatAppSecret);
			LOGGER.info("====getAccessTokenUrl:{}",getAccessTokenUrl);
			try 
			{
				String jsonString = WechatHttpUtils.doGet(getAccessTokenUrl);
				LOGGER.info("===accessToken={}",jsonString);
				JSONObject jsonObj = JSONObject.parseObject(jsonString);
				accessToken = jsonObj.getString("ACCESS_TOKEN");
				startTime = now;
			} 
			catch (Exception e) 
			{
				LOGGER.error("====ex:{}",e);
			}
		}
		else
		{
			try 
			{
				Thread.sleep(OUTTIME);
			} 
			catch (Exception e) 
			{
				LOGGER.error("=======e:{}",e);
			}
		}
		
		return accessToken;
		
	}
}
